package ${package}.${rootArtifactId}.common.util;

import ${package}.${rootArtifactId}.common.exception.BusinessException;

import java.lang.reflect.Method;

/**
 * 发射工具
 *
 * @author weidong.lin
 * @date 2021/7/20 11:14
 */
public class ReflectUtil {

    /**
     * 执行某对象方法
     *
     * @param owner      对象
     * @param methodName 方法名
     * @return 方法返回值
     * @throws Exception
     */
    public static <T> T invokeMethod(Object owner, String methodName, Object... args) {
        T res = null;
        Method method;

        try {
            Class ownerClass = owner.getClass();

            if (args == null) {
                method = ownerClass.getDeclaredMethod(methodName);
                method.setAccessible(true);
                res = (T) method.invoke(owner);
            } else {
                Class[] argsClass = getAragsClass(args);

                method = ownerClass.getDeclaredMethod(methodName, argsClass);
                method.setAccessible(true);
                res = (T) method.invoke(owner, args);
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        return res;
    }

    /**
     * getAragsClass
     *
     * @param args 参数
     * @return Class数组
     */
    private static Class[] getAragsClass(Object... args) {
        Class[] argsClass = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] != null) {
                argsClass[i] = args[i].getClass();
            }
        }
        return argsClass;
    }
}
